# -- coding: utf-8 --
# @time : 2023/5/31
# @author : 周梦泽
# @file : searchRank.py
# @software: pycharm
# 获取搜索排名-生意参谋-市场-搜索排名

import time
from typing import Union, List, Tuple

import pyautogui
import pandas as pd
from autoTask.taobao.sycm.utils.close_Ad import close_ad
from autoTask.taobao.sycm.utils.selectDays import select_days
from autoTask.taobao.taobao_login import Login
from common.logger.log import log_
from common.utils.CacheUtil import init_cache
from common.utils.ExcelUtil import pd_paste_2_csv
from common.utils.ThreadUtil import before_enable_stop_abel_thread
from common.utils.web_page_util import MockTap, Input, random_delay, Tap
from common.utils.web_page_util import create_page

pyautogui.FAILSAFE = False
sycm_url = 'https://sycm.taobao.com/'


# 生意参谋首页url
class SearchRank:

    def __init__(self, params: dict):
        """
        初始化参数
        params: 任务参数，包含
                    ['account': 账号 str,
                   'password':密码 str,
                   'search_content': 搜索内容 str,
                   'date_cycle': 搜索天数 int,
                    'data_word': 搜索词,主题词,长尾词,品牌词,核心词,修饰词 str,
                   ]
        """
        # 提取参数
        self.account = params['account']
        self.password = params['password']
        self.search_content = params['searchContent']
        self.date_cycle = params['dateCycle']
        self.data_word = params['dataWord']
        self.page = create_page()
        self.params = params

    def hot_keywords(self, date_cycle, data_word, search_content) -> Tuple[pd.DataFrame, str]:
        """
        提取热门搜索词路径:市场->搜索排行->搜索词->热搜 -> 选择天数 -> 点击搜索词 -> 点击热搜
        """
        page = self.page
        log_.info('正在打开生意参谋')
        # 跳转到生意参谋首页
        if sycm_url not in page.url:
            page.get(sycm_url)
            time.sleep(3)
        market = page("x://ul[@class='menu-list clearfix']", timeout=3)("tx:市场", timeout=3)
        MockTap(ele=market, msg='点击市场失败', before_delay=(3, 6))()
        search_rank = page("x://div[@class='op-ebase-leftMenu ']/ul[@class='menuList']", timeout=3)("tx:搜索排行",
                                                                                                    timeout=3)
        MockTap(search_rank, msg='点击搜索排行失败', before_delay=(3, 6))()
        while page("资源加载中...", timeout=1) or page("正在努力加载...", timeout=1):
            time.sleep(3)
            page.refresh()
            time.sleep(2)
        MockTap(ele="x://a[@class='common-picker-header']/span", msg='点击输入品类失败', before_delay=(3, 6))(page)
        Input(ele="x://span[@class='oui-canary-input ant-input-affix-wrapper']/input", vals=search_content + '\n',
              before_delay=(3, 6), msg='输入品类失败', after_delay=(5, 8))(page)
        search_content_ele = "x://div[@class='oui-typeahead-dropdown']/div[1]"
        search_content = str(page(search_content_ele, timeout=3).text)
        MockTap(ele=search_content_ele, msg='点击第一个品类失败', before_delay=(3, 6))(page)
        log_.info('选择{}天'.format(date_cycle))
        page, date_cycle = select_days(page, date_cycle)
        log_.info('正在点击 搜索词')
        MockTap(ele=data_word, msg='点击搜索词失败', before_delay=(3, 6))(page)
        log_.info('正在点击 热搜')
        MockTap(ele='热搜', msg='点击热搜失败', before_delay=(3, 6), after_delay=(3, 6))(page)
        # 获取热门搜索词列表，列表中的每个元素转换为文字需要+.text,例如：hot_term_list[0].text
        if page('正值大促期间数据拥堵，请稍后尝试，感谢配合！', timeout=1):
            random_delay((3, 6))
            page.refresh()  # 刷新页面
        log_.info('点击 小旺神一键转化')
        # self.page('小旺神一键转化').click()
        Tap(ele='小旺神一键转化', msg='没找到元素', before_delay=(1, 2))(page)
        # time.sleep(3)
        log_.info('点击一键复制')
        Tap('一键复制', msg='一键复制失败', before_delay=(1, 2))(page)

        data = pd_paste_2_csv()
        data.replace('-', float('nan'), inplace=True)
        # 将-替换为nan
        data.replace(float('nan'), 0)
        # hot_term_list = data['关键词'].tolist()
        # objects = df2datarowobj(data)
        log_.info('关闭小旺神')
        time.sleep(1)
        pyautogui.press('esc')
        return data, search_content

    @before_enable_stop_abel_thread(target_func=close_ad, is_loop=True)
    def __call__(self) -> pd.DataFrame:
        """
         入口函数
         获取缓存，如果缓存存在，直接返回
         如果缓存不存在，hot_keywords-更新缓存
         :return:
         """
        ssph_result = init_cache(self.params).get_search_key_df(key_type='ssph')
        if ssph_result is not None and not ssph_result.empty:
            # 如果返回值不是 None 并且 DataFrame 不为空
            # keywords_obj = df2datarowobj(ssph_result)
            return ssph_result
        Login(self.account, self.password, self.page).execute()
        print(f"芜湖 ： {self.search_content}")
        data, search_content = self.hot_keywords(self.date_cycle, self.data_word, self.search_content)
        self.params['searchContent'] = search_content
        # 更新类目参数名称
        init_cache(self.params).put_cache_by_df(key_type="ssph", df=data)
        # 更新缓存
        return data
